<template>
  <view class="settings-container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-avatar-section">
        <view class="avatar-container">
          <image
            v-if="userInfo.avatar"
            :src="userInfo.avatar"
            class="user-avatar"
            mode="aspectFill"
            @error="handleAvatarError"
          />
          <view v-else class="default-avatar">
            <text class="avatar-text">{{ userInfo.name ? userInfo.name.charAt(0) : 'U' }}</text>
          </view>
        </view>
        <view class="avatar-actions">
          <button class="avatar-btn" @click="uploadAvatar">上传</button>
          <button class="avatar-btn" @click="setAvatarFromURL">链接</button>
          <button v-if="userInfo.avatar" class="avatar-btn remove" @click="removeAvatar">移除</button>
        </view>
      </view>

      <view class="user-info">
        <text class="user-name">{{ userInfo.name || '未设置' }}</text>
        <text class="user-email">{{ userInfo.email || '未设置' }}</text>
        <text class="user-id">ID: {{ userInfo.id || 'N/A' }}</text>
      </view>
    </view>


    <!-- 设置分类 -->
    <view class="settings-categories">
      <!-- 账户设置 -->
      <view class="setting-card" @click="showAccountSettingsModal">
        <view class="setting-icon">👤</view>
        <text class="setting-name">账户设置</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 通知设置 -->
      <view class="setting-card" @click="navigateToNotificationSettings">
        <view class="setting-icon">🔔</view>
        <text class="setting-name">通知设置</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 自动更新 -->
      <view class="setting-card" @click="navigateToUpdateSettings">
        <view class="setting-icon">🔄</view>
        <text class="setting-name">自动更新</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 设备信息 -->
      <view class="setting-card" @click="navigateToDeviceInfo">
        <view class="setting-icon">📱</view>
        <text class="setting-name">设备信息</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 权限管理 -->
      <view class="setting-card" @click="navigateToPermissions">
        <view class="setting-icon">🔐</view>
        <text class="setting-name">权限管理</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 本地数据 -->
      <view class="setting-card" @click="viewLocalData">
        <view class="setting-icon">📊</view>
        <text class="setting-name">查看本地数据</text>
        <text class="setting-arrow">></text>
      </view>

      <!-- 关于应用 -->
      <view class="setting-card" @click="showAboutSettingsModal">
        <view class="setting-icon">ℹ️</view>
        <text class="setting-name">关于应用</text>
        <text class="setting-arrow">></text>
      </view>
    </view>

    <!-- 退出登录按钮 -->
    <view class="logout-section">
      <view class="logout-card" @click="logout">
        <view class="logout-icon">🚪</view>
        <text class="logout-text">退出登录</text>
        <text class="logout-arrow">></text>
      </view>
    </view>

    <!-- 账户设置弹窗 -->
    <view v-if="showAccountModal" class="modal-overlay" @click="closeAccountModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">账户设置</text>
          <text class="modal-close" @click="closeAccountModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="setting-item" @click="editField('name')">
            <view class="setting-icon">👤</view>
            <text class="setting-name">用户名</text>
            <text class="setting-value">{{ userInfo.name || '未设置' }}</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="editField('email')">
            <view class="setting-icon">📧</view>
            <text class="setting-name">邮箱地址</text>
            <text class="setting-value">{{ userInfo.email || '未设置' }}</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="editField('phone')">
            <view class="setting-icon">📱</view>
            <text class="setting-name">手机号码</text>
            <text class="setting-value">{{ userInfo.phone || '未设置' }}</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="editField('birthday')">
            <view class="setting-icon">🎂</view>
            <text class="setting-name">生日</text>
            <text class="setting-value">{{ userInfo.birthday || '未设置' }}</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="editField('bio')">
            <view class="setting-icon">📝</view>
            <text class="setting-name">个人简介</text>
            <text class="setting-value">{{ userInfo.bio || '未设置' }}</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="changePassword">
            <view class="setting-icon">🔒</view>
            <text class="setting-name">修改密码</text>
            <text class="setting-arrow">></text>
          </view>
        </view>
      </view>
    </view>

    <!-- 关于应用弹窗 -->
    <view v-if="showAboutModal" class="modal-overlay" @click="closeAboutModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">关于应用</text>
          <text class="modal-close" @click="closeAboutModal">✕</text>
        </view>
        <view class="modal-body">
          <view class="setting-item" @click="showAbout">
            <view class="setting-icon">ℹ️</view>
            <text class="setting-name">关于我们</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="showHelp">
            <view class="setting-icon">❓</view>
            <text class="setting-name">帮助中心</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="contactUs">
            <view class="setting-icon">📧</view>
            <text class="setting-name">联系我们</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item" @click="showSystemInfo">
            <view class="setting-icon">ℹ️</view>
            <text class="setting-name">系统信息</text>
            <text class="setting-arrow">></text>
          </view>

          <view class="setting-item clickable" @click="checkForUpdates">
            <view class="setting-icon">📱</view>
            <text class="setting-name">版本信息</text>
            <view class="version-info">
              <text class="setting-value">v{{ appVersion }}</text>
              <text class="setting-arrow">></text>
            </view>
          </view>

          <!-- 测试功能按钮 -->
          <view class="setting-item clickable" @click="resetVersionInfo" style="border-top: 1px solid #eee; margin-top: 10px;">
            <view class="setting-icon">🧪</view>
            <text class="setting-name">测试功能</text>
            <view class="version-info">
              <text class="setting-value" style="color: #ff6b6b; font-size: 12px;">重置版本</text>
              <text class="setting-arrow">></text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 热更新进度弹窗 -->
    <view v-if="showUpdateModal" class="modal-overlay" @click="closeUpdateModal">
      <view class="modal-content update-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">应用更新</text>
          <text v-if="!isUpdating" class="modal-close" @click="closeUpdateModal">✕</text>
        </view>
        <view class="modal-body">
          <view v-if="updateInfo" class="update-info">
            <text class="update-title">发现新版本</text>
            <text class="update-version">v{{ updateInfo.latestVersion }}</text>
            <text class="update-message">{{ updateInfo.updateMessage }}</text>
            <text class="update-size">更新大小: {{ formatFileSize(updateInfo.updateSize) }}</text>
            <text v-if="updateInfo.forceUpdate" class="force-update">⚠️ 强制更新</text>
          </view>

          <view v-if="isUpdating" class="update-progress">
            <text class="progress-title">{{ updateProgressText }}</text>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: updateProgress + '%' }"></view>
            </view>
            <text class="progress-percent">{{ updateProgress }}%</text>
            <text v-if="currentUpdateFile" class="progress-file">{{ currentUpdateFile }}</text>
          </view>

          <view v-if="!isUpdating" class="update-actions">
            <button class="update-btn primary" @click="startUpdate" :disabled="!updateInfo">
              立即更新
            </button>
            <button v-if="!updateInfo.forceUpdate" class="update-btn secondary" @click="closeUpdateModal">
              稍后再说
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import zipHotUpdate from '@/utils/wgt-hot-update.js'
import config from '@/utils/config.js'

export default {
  data() {
    return {
      appVersion: '1.0.3',
      userInfo: {
        id: '',
        name: '',
        email: '',
        phone: '',
        birthday: '',
        bio: '',
        avatar: ''
      },
      // 弹窗状态控制
      showAccountModal: false,
      showAboutModal: false,
      showUpdateModal: false,
      // 热更新相关
      updateInfo: null,
      isUpdating: false,
      updateProgress: 0,
      updateProgressText: '',
      currentUpdateFile: ''
    }
  },

  onLoad() {
    this.loadUserInfo()
    this.loadAppVersion()
  },
  
  // 处理返回按钮（APP平台）
  // #ifdef APP-PLUS
  onBackPress() {
    // 检查页面栈，如果有上一页则返回，否则跳转到首页
    const pages = getCurrentPages()
    if (pages.length > 1) {
      // 有上一页，正常返回
      return false // 返回 false 表示不拦截，使用默认返回行为
    } else {
      // 没有上一页，跳转到首页
      uni.reLaunch({
        url: '/pages/index/index'
      })
      return true // 返回 true 表示已处理，拦截默认返回行为
    }
  },
  // #endif
  
  // H5平台：使用 onUnload 或监听页面卸载
  // #ifdef H5
  onUnload() {
    // H5平台返回按钮由浏览器处理，这里不需要特殊处理
    // 但如果页面栈被清空，可能需要检查
    const pages = getCurrentPages()
    if (pages.length <= 1) {
      // 如果页面栈只有当前页，说明可能是直接访问的，不做处理
      // 因为 H5 的返回按钮由浏览器控制
    }
  },
  // #endif

  methods: {
    // 弹窗控制方法
    showAccountSettingsModal() {
      this.showAccountModal = true
    },

    closeAccountModal() {
      this.showAccountModal = false
    },


    showAboutSettingsModal() {
      this.showAboutModal = true
    },

    closeAboutModal() {
      this.showAboutModal = false
    },

    // 查看本地数据
    viewLocalData() {
      uni.navigateTo({
        url: '/pages/settings/local-data/local-data'
      })
    },

    // 导航到通知设置
    navigateToNotificationSettings() {
      uni.navigateTo({
        url: '/pages/settings/notification-settings/notification-settings'
      })
    },

    // 导航到更新设置
    navigateToUpdateSettings() {
      uni.navigateTo({
        url: '/pages/settings/update-settings/update-settings'
      })
    },

    // 导航到设备信息
    navigateToDeviceInfo() {
      uni.navigateTo({
        url: '/pages/settings/device-info/device-info'
      })
    },

    // 导航到权限管理
    navigateToPermissions() {
      uni.navigateTo({
        url: '/pages/settings/permissions/permissions'
      })
    },

    closeUpdateModal() {
      this.showUpdateModal = false
      this.updateInfo = null
      this.isUpdating = false
      this.updateProgress = 0
      this.updateProgressText = ''
      this.currentUpdateFile = ''
    },


    // 加载应用版本
    async loadAppVersion() {
      try {
        // 优先从本地存储读取（更新后的版本）
        const savedVersion = uni.getStorageSync('app_version')
        console.log('本地存储中的版本:', savedVersion)

        if (savedVersion) {
          this.appVersion = savedVersion
          console.log('从本地存储读取版本:', this.appVersion)
          return
        }

        // #ifdef H5
        // H5环境：从update-info.json读取版本
        try {
          const response = await fetch('/update-info.json')
          if (response.ok) {
            const updateInfo = await response.json()
            this.appVersion = updateInfo.version || '1.0.0'
            uni.setStorageSync('app_version', this.appVersion)
            console.log('从update-info.json读取版本:', this.appVersion)
            return
          }
        } catch (error) {
          console.log('无法从update-info.json读取版本:', error)
        }
        // #endif

        // #ifdef APP-PLUS
        // APP环境：从plus.runtime.getProperty读取版本
        try {
          if (typeof plus !== 'undefined' && plus.runtime) {
            // 使用getProperty获取应用信息
            plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
              console.log('应用信息:', widgetInfo)
              const manifestVersion = widgetInfo.version
              console.log('从plus.runtime.getProperty获取的版本:', manifestVersion)

              if (manifestVersion) {
                this.appVersion = manifestVersion
                uni.setStorageSync('app_version', this.appVersion)
                console.log('从plus.runtime.getProperty读取版本:', this.appVersion)
              } else {
                // 如果getProperty失败，使用默认版本
                this.appVersion = '1.3.1'
                uni.setStorageSync('app_version', this.appVersion)
                console.log('使用默认版本:', this.appVersion)
              }
            }, (error) => {
              console.error('获取应用信息失败:', error)
              // 如果getProperty失败，使用默认版本
              this.appVersion = '1.3.1'
              uni.setStorageSync('app_version', this.appVersion)
              console.log('getProperty失败，使用默认版本:', this.appVersion)
            })
            return
          }
          console.log('plus.runtime不可用')
        } catch (error) {
          console.error('读取应用版本失败:', error)
        }
        // #endif

        // 默认版本
        this.appVersion = '1.0.0'
        uni.setStorageSync('app_version', this.appVersion)

      } catch (error) {
        console.error('加载版本信息失败:', error)
        this.appVersion = '1.0.0'
        uni.setStorageSync('app_version', this.appVersion)
      }
    },

    // 重置版本信息（测试功能）
    resetVersionInfo() {
      uni.showModal({
        title: '测试功能',
        content: '确定要重置版本信息吗？\n\n这将清除所有版本相关的本地存储数据，应用将重新读取版本号',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定重置',
        confirmColor: '#ff6b6b',
        success: (res) => {
          if (res.confirm) {
            try {
              // 清除版本相关的本地存储
              uni.removeStorageSync('app_version')
              uni.removeStorageSync('update_info')

              // 重新加载版本信息
              this.loadAppVersion()

              // 显示成功提示
              uni.showToast({
                title: '版本信息已重置',
                icon: 'success',
                duration: 2000
              })

              console.log('版本信息已重置，重新加载版本号')

            } catch (error) {
              console.error('重置版本信息失败:', error)
              uni.showToast({
                title: '重置失败',
                icon: 'error',
                duration: 2000
              })
            }
          }
        }
      })
    },

    // 检查版本更新
    async checkForUpdates() {
      // #ifdef H5
      // H5环境不需要热更新功能
      uni.showModal({
        title: '版本信息',
        content: `当前版本：v${this.appVersion}\n\nH5版本会自动更新，请刷新页面获取最新版本。`,
        showCancel: false,
        confirmText: '确定'
      })
      return
      // #endif

      // #ifdef APP-PLUS
      try {
        uni.showLoading({
          title: '检查更新中...',
          mask: true
        })

        // 配置Gitee信息（请替换为你的实际信息）
        zipHotUpdate.setGiteeConfig('xuxinzhi2206', 'moe_web', '')

        // 检查更新
        const updateResult = await zipHotUpdate.checkForUpdate()

        uni.hideLoading()

        if (updateResult.hasUpdate) {
          const remoteInfo = updateResult.updateInfo || {}
          const latestVersion = remoteInfo.version || updateResult.remoteVersion || ''

          this.updateInfo = {
            latestVersion,
            currentVersion: updateResult.currentVersion || '',
            updateMessage: remoteInfo.updateMessage || remoteInfo.message || updateResult.message || '发现新版本',
            updateSize: Number(remoteInfo.size) || 0,
            downloadUrl: remoteInfo.downloadUrl || zipHotUpdate.getDownloadUrl(),
            forceUpdate: !!remoteInfo.forceUpdate,
            rawUpdateInfo: remoteInfo
          }

          this.showUpdateModal = true
        } else {
          uni.showModal({
            title: '版本检查',
            content: `当前版本：v${updateResult.currentVersion}\n\n${updateResult.message}`,
            showCancel: false,
            confirmText: '确定'
          })
        }

      } catch (error) {
        uni.hideLoading()
        console.error('检查更新失败:', error)

        // 根据错误类型显示不同的提示信息
        let errorMessage = '网络连接异常，请稍后重试'

        if (error.message) {
          if (error.message.includes('网络访问受限')) {
            errorMessage = '网络访问受限，请检查网络连接或稍后重试'
          } else if (error.message.includes('404')) {
            errorMessage = '版本信息文件不存在，请联系开发者'
          } else if (error.message.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接'
          } else {
            errorMessage = error.message
          }
        }

        // 检查是否是H5平台的下载限制
        if (error.message && error.message.includes('H5平台暂不支持自动下载')) {
          // #ifdef H5
          uni.showModal({
            title: '更新提示',
            content: '由于浏览器安全限制，网页版暂不支持自动下载更新包。\n\n请手动下载更新包：\n1. 点击确定打开下载链接\n2. 下载完成后解压到应用目录\n3. 刷新页面即可完成更新',
            showCancel: true,
            cancelText: '取消',
            confirmText: '下载更新',
            success: (res) => {
              if (res.confirm && this.updateInfo) {
                // 打开下载链接
                window.open(this.updateInfo.updateUrl, '_blank')
              }
            }
          })
          // #endif

          // #ifdef APP-PLUS
          // APP平台显示正常错误信息
          uni.showModal({
            title: '检查更新失败',
            content: errorMessage,
            showCancel: false,
            confirmText: '确定'
          })
          // #endif
        } else {
          // #ifdef APP-PLUS
          uni.showModal({
            title: '检查更新失败',
            content: errorMessage,
            showCancel: false,
            confirmText: '确定'
          })
          // #endif
        }
      }
      // #endif
    },

    // 开始更新
    async startUpdate() {
      if (!this.updateInfo) return

      try {
        this.isUpdating = true
        this.updateProgress = 0
        this.updateProgressText = '准备更新...'

        // 下载并应用更新
        const updateMeta = this.updateInfo.rawUpdateInfo || {
          version: this.updateInfo.latestVersion,
          updateMessage: this.updateInfo.updateMessage,
          size: this.updateInfo.updateSize,
          forceUpdate: this.updateInfo.forceUpdate
        }

        const downloadUrl = this.updateInfo.downloadUrl

        const result = await zipHotUpdate.downloadAndApplyUpdate(
          downloadUrl,
          updateMeta,
          (progress) => {
            this.updateProgress = progress.progress
            this.updateProgressText = progress.message
            this.currentUpdateFile = progress.currentFile || ''
          }
        )

        if (result.success) {
          this.updateProgress = 100
          this.updateProgressText = '更新完成'

          // 更新本地版本显示
          const newVersion = updateMeta.version || this.updateInfo.latestVersion || this.appVersion
          this.appVersion = newVersion

          setTimeout(() => {
            this.closeUpdateModal()

            uni.showModal({
              title: '更新完成',
              content: `应用已更新到 v${this.appVersion}！\n\n✅ wgt包安装成功\n应用将在3秒后自动重启以应用更新。`,
              showCancel: false,
              confirmText: '确定',
              success: (res) => {
                if (res.confirm) {
                  console.log('用户确认更新完成')
                }
              }
            })
          }, 1000)
        }

      } catch (error) {
        this.isUpdating = false
        console.error('更新失败:', error)

        uni.showModal({
          title: '更新失败',
          content: error.message || '更新过程中出现错误，请重试',
          showCancel: false,
          confirmText: '确定'
        })
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      const value = Number(bytes)

      if (value === 0) return '0 B'
      if (!Number.isFinite(value) || value < 0) return '未知大小'

      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const index = Math.min(Math.floor(Math.log(value) / Math.log(k)), sizes.length - 1)

      const formatted = value / Math.pow(k, index)
      return `${parseFloat(formatted.toFixed(2))} ${sizes[index]}`
    },

    async loadUserInfo() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (currentUser) {
          const userData = JSON.parse(currentUser)

          // 如果用户数据中没有ID，尝试通过邮箱获取
          if (!userData.id && userData.email) {
            try {
              const userId = await apiService.getUserId(userData)
              if (userId) {
                userData.id = userId
                // 更新本地存储
                uni.setStorageSync('currentUser', JSON.stringify(userData))
              }
            } catch (error) {
              console.log('获取用户ID失败:', error)
            }
          }

          this.userInfo = { ...this.userInfo, ...userData }
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
      }
    },

    // 用户信息编辑方法
    editField(field) {
      const fieldNames = {
        name: '用户名',
        email: '邮箱地址',
        phone: '手机号码',
        birthday: '生日',
        bio: '个人简介'
      }

      uni.showModal({
        title: `编辑${fieldNames[field]}`,
        editable: true,
        placeholderText: `请输入${fieldNames[field]}`,
        content: this.userInfo[field] || '',
        success: (res) => {
          if (res.confirm && res.content !== undefined) {
            const newValue = res.content.trim()
            if (newValue !== this.userInfo[field]) {
              // 如果是邮箱字段，需要特殊处理
              if (field === 'email') {
                this.handleEmailChange(newValue)
              } else {
                this.userInfo[field] = newValue
                this.updateUserInfoToServer(field, newValue)
              }
            }
          }
        }
      })
    },

    // 处理邮箱修改
    async handleEmailChange(newEmail) {
      // 验证邮箱格式
      if (!this.isValidEmail(newEmail)) {
        uni.showToast({
          title: '请输入有效的邮箱地址',
          icon: 'error',
          duration: 2000
        })
        return
      }

      // 检查邮箱是否与当前邮箱相同
      if (newEmail === this.userInfo.email) {
        uni.showToast({
          title: '新邮箱与当前邮箱相同',
          icon: 'none',
          duration: 2000
        })
        return
      }

      try {
        // 先检查邮箱是否已存在
        uni.showLoading({
          title: '检查邮箱...'
        })

        const emailExists = await this.checkEmailExists(newEmail)

        if (emailExists) {
          uni.hideLoading()
          uni.showToast({
            title: '该邮箱已被注册，请使用其他邮箱',
            icon: 'error',
            duration: 3000
          })
          return
        }

        // 邮箱不存在，可以更新
        uni.showLoading({
          title: '更新邮箱...'
        })

        // 更新用户信息
        this.userInfo.email = newEmail
        await this.updateUserInfoToServer('email', newEmail)

        uni.hideLoading()
        uni.showToast({
          title: '邮箱更新成功',
          icon: 'success',
          duration: 2000
        })

      } catch (error) {
        uni.hideLoading()
        console.error('邮箱更新失败:', error)

        // 回滚本地修改
        this.loadUserInfo()

        // 根据错误类型显示不同的提示
        if (error.message && error.message.includes('已被注册')) {
          uni.showToast({
            title: '该邮箱已被注册，请使用其他邮箱',
            icon: 'error',
            duration: 3000
          })
        } else if (error.message && error.message.includes('离线模式')) {
          // 离线模式下，检查本地数据
          if (this.checkLocalEmailExists(newEmail)) {
            uni.showToast({
              title: '该邮箱已被注册，请使用其他邮箱',
              icon: 'error',
              duration: 3000
            })
          } else {
            // 本地数据中没有重复，直接保存
            this.userInfo.email = newEmail
            this.saveUserInfo()
            uni.showToast({
              title: '邮箱更新成功（离线模式）',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          uni.showToast({
            title: error.message || '邮箱更新失败，请重试',
            icon: 'error',
            duration: 2000
          })
        }
      }
    },

    // 验证邮箱格式
    isValidEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(email)
    },

    // 检查邮箱是否已存在
    async checkEmailExists(email) {
      try {
        // 尝试通过API查询用户信息来检查邮箱是否存在
        await apiService.getUserInfo(email)
        // 如果能成功获取用户信息，说明邮箱已存在
        return true
      } catch (error) {
        // 如果是404错误，说明用户不存在，邮箱可用
        if (error.status === 404 || (error.message && error.message.includes('404'))) {
          return false
        }
        // 其他错误（如网络错误），抛出异常让上层处理
        throw error
      }
    },

    // 检查本地邮箱是否已存在
    checkLocalEmailExists(email) {
      try {
        const users = JSON.parse(uni.getStorageSync('users') || '[]')
        return users.some(user => user.email === email && user.email !== this.userInfo.email)
      } catch (error) {
        console.error('检查本地邮箱失败:', error)
        return false
      }
    },

    saveUserInfo() {
      try {
        // 保存当前用户信息
        uni.setStorageSync('currentUser', JSON.stringify(this.userInfo))

        // 同时更新用户列表中的信息
        const usersData = uni.getStorageSync('users')
        if (usersData) {
          const users = JSON.parse(usersData)
          const updatedUsers = users.map(user => {
            if (user.email === this.userInfo.email || user.id === this.userInfo.id) {
              return { ...user, ...this.userInfo }
            }
            return user
          })
          uni.setStorageSync('users', JSON.stringify(updatedUsers))
        }

        console.log('用户信息已保存:', this.userInfo)
      } catch (error) {
        console.error('保存用户信息失败:', error)
      }
    },

    // 头像相关方法
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          // 注意：由于API接口限制，这里暂时使用本地路径
          // 实际项目中需要将图片上传到服务器获取URL
          this.updateUserAvatarToServer(tempFilePath)
        },
        fail: (error) => {
          console.log('选择头像失败或用户取消:', error)
          if (error.errMsg && !error.errMsg.includes('cancel')) {
            uni.showToast({
              title: '选择头像失败',
              icon: 'error'
            })
          }
        }
      })
    },

    setAvatarFromURL() {
      uni.showModal({
        title: '设置头像链接',
        editable: true,
        placeholderText: '请输入图片链接地址',
        success: (res) => {
          if (res.confirm && res.content && res.content.trim()) {
            const url = res.content.trim()
            if (this.isValidImageURL(url)) {
              this.updateUserAvatarToServer(url)
            } else {
              uni.showToast({
                title: '请输入有效的图片链接',
                icon: 'error',
                duration: 2000
              })
            }
          }
        },
        fail: (error) => {
          console.log('用户取消设置头像链接:', error)
        }
      })
    },

    isValidImageURL(url) {
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']
      const lowerUrl = url.toLowerCase()
      return imageExtensions.some(ext => lowerUrl.includes(ext)) ||
             lowerUrl.includes('data:image/') ||
             lowerUrl.includes('blob:')
    },

    updateUserAvatar(avatarUrl) {
      this.userInfo.avatar = avatarUrl
      this.saveUserInfo()
    },

    removeAvatar() {
      uni.showModal({
        title: '移除头像',
        content: '确定要移除当前头像吗？',
        success: (res) => {
          if (res.confirm) {
            this.userInfo.avatar = ''
            this.saveUserInfo()
            uni.showToast({
              title: '头像已移除',
              icon: 'success',
              duration: 2000
            })
          }
        }
      })
    },

    handleAvatarError() {
      console.log('头像加载失败')
      this.userInfo.avatar = ''
      this.saveUserInfo()
    },

    // 更新用户信息到服务器
    async updateUserInfoToServer(field, value) {
      try {
        const updateData = {
          [field]: value
        }

        // 调用API更新用户信息
        const result = await apiService.updateUserInfo(this.userInfo.email, updateData)

        // 更新本地存储
        this.saveUserInfo()

        console.log('用户信息更新成功:', result)

        return result

      } catch (error) {
        console.error('更新用户信息失败:', error)

        // 抛出错误，让调用方处理
        throw error
      }
    },

    // 更新用户头像到服务器
    async updateUserAvatarToServer(avatarUrl) {
      try {
        uni.showLoading({
          title: '设置中...'
        })

        // 调用API更新头像
        const result = await apiService.updateAvatar(this.userInfo.email, avatarUrl)

        // 更新本地用户信息
        this.userInfo.avatar = avatarUrl
        this.saveUserInfo()

        uni.hideLoading()
        uni.showToast({
          title: '头像设置成功',
          icon: 'success'
        })

        console.log('头像更新成功:', result)

      } catch (error) {
        uni.hideLoading()
        console.error('更新头像失败:', error)

        uni.showToast({
          title: error.message || '头像设置失败，请重试',
          icon: 'error',
          duration: 2000
        })
      }
    },

    changePassword() {
      uni.showModal({
        title: '修改密码',
        editable: true,
        placeholderText: '请输入新密码',
        success: (res) => {
          if (res.confirm && res.content && res.content.trim()) {
            const newPassword = res.content.trim()
            if (newPassword.length < 6) {
              uni.showToast({
                title: '密码长度至少6位',
                icon: 'error'
              })
              return
            }
            this.updatePasswordToServer(newPassword)
          }
        }
      })
    },

    // 更新密码到服务器
    async updatePasswordToServer(newPassword) {
      try {
        uni.showLoading({
          title: '修改中...'
        })

        const updateData = {
          password: newPassword
        }

        // 调用API更新密码
        const result = await apiService.updateUserInfo(this.userInfo.email, updateData)

        uni.hideLoading()
        uni.showToast({
          title: '密码修改成功',
          icon: 'success'
        })

        console.log('密码更新成功:', result)

      } catch (error) {
        uni.hideLoading()
        console.error('更新密码失败:', error)

        uni.showToast({
          title: error.message || '密码修改失败，请重试',
          icon: 'error'
        })
      }
    },

    logout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出当前账户吗？',
        success: (res) => {
          if (res.confirm) {
            this.performLogout()
          }
        }
      })
    },

    // 执行退出登录
    async performLogout() {
      try {
        // 记录退出时间（在清除 token 之前）
        const goldManagerModule = await import('@/utils/gold-manager.js')
        const goldManager = goldManagerModule.default || goldManagerModule
        if (goldManager && typeof goldManager.recordLogoutTime === 'function') {
          goldManager.recordLogoutTime()
        }
        
        // 清除登录状态
        const keysToRemove = [
          'user_token', 'currentUser', 'currentToken', 'isServerLogin',
          'user_info', 'user_settings', 'friends_list', 'chat_messages',
          'friend_requests', 'last_sync_time', 'sync_history',
          'offline_user_data', 'local_chat_data', 'notification_settings'
        ]
        
        keysToRemove.forEach(key => {
          try {
            uni.removeStorageSync(key)
          } catch (error) {
            console.log(`清除存储项 ${key} 失败:`, error)
          }
        })
        
        // 清除所有用户的积分数据
        // 动态导入 pointsManager
        const pointsManagerModule = await import('@/utils/points-manager.js')
        const pointsManager = pointsManagerModule.default || pointsManagerModule
        if (pointsManager && typeof pointsManager.clearAllUsersData === 'function') {
          pointsManager.clearAllUsersData()
        }

        uni.showToast({
          title: '已退出登录',
          icon: 'success',
          duration: 1500
        })

        // 保留在当前页面，不强制跳转
        setTimeout(() => {
          const pages = getCurrentPages()
          if (pages.length > 1) {
            // 有上一页，返回上一页
            uni.navigateBack()
          } else {
            // 没有上一页，跳转到首页
            uni.reLaunch({ url: '/pages/index/index' })
          }
        }, 1500)
      } catch (error) {
        console.error('退出登录失败:', error)
        uni.showToast({ title: '退出登录失败', icon: 'error' })
      }
    },


    showAbout() {
      uni.showModal({
        title: '关于应用',
        content: `荒岛生存 v${this.appVersion}\n\n一个有趣的生存游戏，在荒岛上努力生存下去！\n\n开发者：Moe Team\n更新时间：2024年`,
        showCancel: false
      })
    },

    showSystemInfo() {
      const envInfo = this.getEnvironmentInfo()
      const info = `环境: ${envInfo.environment}\n平台: ${envInfo.platform}\n服务器: ${envInfo.serverURL}`
      uni.showModal({
        title: '系统信息',
        content: info,
        showCancel: false
      })
    },

    getEnvironmentInfo() {
      // 使用统一的配置获取环境信息
      const envInfo = config.getEnvironmentInfo()
      return {
        environment: envInfo.isDevelopment ? '开发环境' : '生产环境',
        platform: envInfo.platform === 'web' ? 'H5' : envInfo.platform,
        serverURL: envInfo.serverURL
      }
    },

    showHelp() {
      uni.showModal({
        title: '帮助中心',
        content: '这是一个用户管理系统，提供用户注册、登录、游戏娱乐等功能。如有问题请联系管理员。',
        showCancel: false
      })
    },

    contactUs() {
      uni.showModal({
        title: '联系我们',
        content: '如有问题或建议，请通过以下方式联系我们：\n\n邮箱：support@moe.com\nQQ群：123456789',
        showCancel: false
      })
    },

    navigateToIndex() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.settings-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
}

/* 用户信息卡片样式 */
.user-card {
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.user-avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.avatar-container {
  position: relative;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid #f0f0f0;
}

.default-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4rpx solid #f0f0f0;
}

.avatar-text {
  color: white;
  font-size: 48rpx;
  font-weight: bold;
}

.avatar-actions {
  display: flex;
  gap: 8rpx;
}

.avatar-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6rpx;
  padding: 8rpx 12rpx;
  font-size: 20rpx;
  min-width: 60rpx;
  height: 32rpx;
  line-height: 16rpx;
}

.avatar-btn.remove {
  background: #e74c3c;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #2d3436;
}

.user-email {
  font-size: 24rpx;
  color: #636e72;
}

.user-id {
  font-size: 20rpx;
  color: #b2bec3;
}

.settings-categories {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.setting-card {
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 24rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.setting-card:active {
  transform: scale(0.98);
  background: #f8f9fa;
}

.setting-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
  min-height: 80rpx;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-item:active {
  background-color: #f8f9fa;
}

.setting-item.clickable {
  cursor: pointer;
}

.setting-item.clickable:active {
  background-color: #f0f8ff;
}

.setting-item.logout-item {
  border-bottom: none;
  margin-top: 10rpx;
  border-top: 1rpx solid #f0f0f0;
}

.setting-icon {
  font-size: 28rpx;
  margin-right: 16rpx;
  width: 32rpx;
  text-align: center;
}

.setting-name {
  flex: 1;
  font-size: 26rpx;
  color: #2d3436;
  font-weight: 500;
}

.setting-value {
  font-size: 24rpx;
  color: #636e72;
  margin-right: 12rpx;
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.setting-arrow {
  font-size: 20rpx;
  color: #b2bec3;
}

/* 版本信息样式 */
.version-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.version-info .setting-value {
  margin-right: 0;
}

.version-info .setting-arrow {
  font-size: 20rpx;
  color: #b2bec3;
}

/* 更新弹窗样式 */
.update-modal {
  max-width: 700rpx;
}

.update-info {
  padding: 20rpx;
  text-align: center;
}

.update-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #2d3436;
  margin-bottom: 16rpx;
  display: block;
}

.update-version {
  font-size: 28rpx;
  color: #667eea;
  font-weight: bold;
  margin-bottom: 12rpx;
  display: block;
}

.update-message {
  font-size: 24rpx;
  color: #636e72;
  margin-bottom: 8rpx;
  display: block;
}

.update-size {
  font-size: 22rpx;
  color: #b2bec3;
  margin-bottom: 4rpx;
  display: block;
}

.force-update {
  font-size: 20rpx;
  color: #e74c3c;
  font-weight: bold;
  display: block;
}

.update-progress {
  padding: 20rpx;
  text-align: center;
}

.progress-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #2d3436;
  margin-bottom: 20rpx;
  display: block;
}

.progress-bar {
  width: 100%;
  height: 8rpx;
  background: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
  margin-bottom: 16rpx;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transition: width 0.3s ease;
}

.progress-percent {
  font-size: 24rpx;
  color: #636e72;
  margin-bottom: 8rpx;
  display: block;
}

.progress-file {
  font-size: 20rpx;
  color: #b2bec3;
  display: block;
}

.update-actions {
  padding: 20rpx;
  display: flex;
  gap: 16rpx;
}

.update-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  border: none;
  transition: all 0.3s ease;
}

.update-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.update-btn.primary:active {
  transform: scale(0.98);
}

.update-btn.secondary {
  background: #f8f9fa;
  color: #636e72;
  border: 2rpx solid #e9ecef;
}

.update-btn.secondary:active {
  background: #e9ecef;
}

.update-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  padding: 40rpx;
}

.modal-content {
  background: white;
  border-radius: 20rpx;
  width: 100%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  animation: modalSlideIn 0.3s ease;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20rpx);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.modal-close {
  font-size: 28rpx;
  cursor: pointer;
  padding: 8rpx;
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.modal-close:active {
  background: rgba(255, 255, 255, 0.2);
}

.modal-body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0;
}

/* 退出登录按钮样式 */
.logout-section {
  margin-top: 30rpx;
}

.logout-card {
  background: white;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  padding: 24rpx 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2rpx solid #e74c3c;
}

.logout-card:active {
  transform: scale(0.98);
  background: #fdf2f2;
  border-color: #c0392b;
}

.logout-icon {
  font-size: 28rpx;
  color: #e74c3c;
  width: 32rpx;
  text-align: center;
}

.logout-text {
  flex: 1;
  font-size: 26rpx;
  color: #e74c3c;
  font-weight: 500;
}

.logout-arrow {
  font-size: 20rpx;
  color: #e74c3c;
}
</style>
